home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 6_11.lha / 6_11 / 6_11_neg.c < prev    next >
Text File  |  1993-08-08  |  1KB  |  67 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. *
  6.    Negate u[1..n] to form w[0..n]
  7.    Uses a variation on:
  8.  
  9.    The Art of Computer Programming, volume 2
  10.    D. Knuth, Section 4.3.1, Algorithm A
  11. /
  12. include <arbint.h>
  13. include <debug.h>    // DELETE
  14.  
  15. rbint operator-(const arbint& u)
  16.  
  17.    int ulen = u.p->length;
  18.    int wlen = ulen + u.isneg();
  19.    ARB_type *wv = new ARB_type[wlen];
  20.    ARB_type *uv = u.p->value;
  21.  
  22. bug&4)    outputarb(cerr, "\n\nneg:\nu=", uv, ulen);        // DELETE
  23.    /*
  24. A1 [Initialize]
  25.     set j <- n
  26.     k <- 0
  27. becomes
  28.     k <- 1
  29.  
  30. A3(a) [Loop on j]
  31.     decrease j by one
  32.    */
  33.    ARB_Ltype k = 1;
  34.    for (int uj = ulen - 1, wj = wlen - 1;
  35.  uj >= 0; uj--, wj--)
  36. {
  37. /*
  38.     A2(a) [Add digits]
  39.     set w[j] <- (u[j] + v[j] + k) mod b
  40.     becomes
  41.     set w[j] <- (~u[j] + k) mod b
  42. */
  43. ARB_type l1 = ~uv[uj];
  44. ARB_Ltype l = l1 + k;
  45. wv[wj] = l;    // % ARB_based
  46. /*
  47.     A2(b)
  48.     k <- (u[j] + v[j] + k) / b
  49. */
  50. k = (l / ARB_base ) ? 1 : 0;
  51. }
  52.  
  53.    /*
  54. A3(b)
  55.     Set w[0] <- ~0 + k
  56.    */
  57.    if (wj == 0)
  58.        { if (debug&4) cerr << "wj==0, k=" << k << "\n";    // DELETE
  59. wv[0] = k ? ~0 : 0;
  60. }    // DELETE
  61.  
  62.    /* Normalize and return */
  63. f (debug&4)    outputarb(cerr, "wv=", wv, wlen);        // DELETEd    arbint w(wv, wlen);
  64. f (debug&4)    outputarb(cerr, "w=", w.p->value, w.p->length);        // DELETE
  65.    return w;
  66.  
  67.